package com.dmxh.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.dmxh.pojo.TbUser;
import com.dmxh.result.Result;
import com.dmxh.result.ResultConstant;
import com.dmxh.service.UserService;
import com.dmxh.util.JwtUtil;
import com.dmxh.vo.UserVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/*前端网站页面 登录 操作*/
@RestController
@RequestMapping("/login")
public class LoginUserController {

    @Autowired
    private UserService userService;

    @PostMapping("/userlogin")/*@RequestParam("username")String username, @RequestParam("password")String password*/
    public Result userlogin(@RequestBody Map<String,String> loginForm){
        String username = loginForm.get("username");
        String password = loginForm.get("password");

        /*获取subject对象*/
        Subject subject = SecurityUtils.getSubject();
        /*封装数据*/
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,password);
        try {
            /*进入认证方法*/
            subject.login(usernamePasswordToken);
        } catch (UnknownAccountException unknownAccountException) {
            unknownAccountException.printStackTrace();
            return Result.response(ResultConstant.USERNAME_PASSWORD_ERROR_DATA);/*用戶名错誤*/
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            return Result.response(ResultConstant.USERNAME_PASSWORD_ERROR_DATA);/*密码错误*/
        }
        //校验JWT   生成token
        TbUser principal = (TbUser) SecurityUtils.getSubject().getPrincipal();/*拿到了用户名  通过用户名去查询这条信息*/
        /*拿到当前用户信息  根据当前用户信息去生成token*/
        //脱敏处理
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(principal,userVO);
        String token = JwtUtil.createJwt(userVO.getId().toString(), JSONObject.toJSONString(userVO), "roles");
        return Result.response(ResultConstant.SUCCESS_LOGIN).setData(token);/*将通过用户信息生成好的token返回给用户*/
    }
}
